package com.erp.tool;

import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;


@Component
public class EmailTool {
    @Autowired
    private JavaMailSenderImpl javaMailSender;
    public String emailGive(String subject, String text, String to, InputStream is) throws MessagingException, IOException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
//        主题
        helper.setSubject(subject);
//        正文
        helper.setText(text,true);
        //携带附件
        // 设置附件
        XSSFWorkbook workbook = new XSSFWorkbook(is);
        InputStream in = null;
        try {

            //临时缓冲区
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            //创建临时文件
            workbook.write(out);
            byte[] bookByteAry = out.toByteArray();
            in = new ByteArrayInputStream(bookByteAry);
        } catch (Exception e) {
//            logger.error("export orderList error!", e);
        }
        helper.addAttachment("采购计划需求.xlsx", new ByteArrayResource(IOUtils.toByteArray(in)), "application/vnd.ms-excel;charset=UTF-8");
//        发送人
        helper.setFrom("fixiaobai@163.com");
//        收件人
        helper.setTo(to);

        javaMailSender.send(mimeMessage);
        return "success";
    }
}
